package com.px.pa.modulars.hsh;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.support.cache.RedisHelper;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.basic.alone.security.jwt.JwtTokenUtil;
import com.px.basic.alone.security.jwt.payload.JwtPayLoad;
import com.px.pa.modulars.circle.entity.*;
import com.px.pa.modulars.circle.service.*;
import com.px.wx.mini.config.WxMaConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/hshcircleuser")
@Api(value = "hshcircleuser", tags = "")
public class HshLoginController {

    private final CircleUserService circleUserService;
    private final CircleWxInfoService circleWxInfoService;
    @Autowired
    private RedisHelper redisHelper;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private CircleEnableService circleEnableService;
    @Autowired
    private CircleCompanyService circleCompanyService;

    private final CircleCodeService circleCodeService;


    private final UserRegLogService userRegLogService;




    /**
     * 手机号直接登录
     */
    @GetMapping(value = "/phone/login")
    @ApiOperation("手机号直接登录")
    @Inner(value = false)
    public Object phoneLogin(@RequestParam(value = "phone") String phone, @RequestParam(value = "code") String code, @RequestParam(value = "phoneCode") String phoneCode


    ) {
        Map<String, Object> result = new HashMap<>();
        //查询万能码
        List<CircleCode> circleCodeList = circleCodeService.list();
        if (circleCodeList.size() != 0) {
            CircleCode circleCode = circleCodeList.get(0);
            if (StringUtils.isNotEmpty(circleCode.getCode())) {

                if (!circleCode.getCode().equals(phoneCode)) {
                    if (redisTemplate.opsForValue().get(phone) == null) {
                        return R.failed("验证码失效");
                    }
                    if (!redisTemplate.opsForValue().get(phone).equals(phoneCode)) {
                        return R.failed("验证码不正确");
                    }
                }
            } else {
                if (redisTemplate.opsForValue().get(phone) == null) {
                    return R.failed("验证码失效");
                }
                if (!redisTemplate.opsForValue().get(phone).equals(phoneCode)) {
                    return R.failed("验证码不正确");
                }
            }
        } else {
            if (redisTemplate.opsForValue().get(phone) == null) {
                return R.failed("验证码失效");
            }
            if (!redisTemplate.opsForValue().get(phone).equals(phoneCode)) {
                return R.failed("验证码不正确");
            }

        }

        CircleWxInfo circleWxInfo = circleWxInfoService.list().get(0);
        String wxOpenid = null;

        final WxMaService wxService = WxMaConfiguration.getMaService(circleWxInfo.getAppid(), circleWxInfo.getSecret());
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            wxOpenid = session.getOpenid();
            //通过openid 查询用户信息把用户信息的openid设为空
            CircleUser circleUser2 = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(StringUtils.isNotEmpty(wxOpenid), "open_id", wxOpenid));
            if (circleUser2 != null) {
                if (StringUtils.isNotEmpty(circleUser2.getToken())) {
                    redisTemplate.delete(circleUser2.getToken());
                }
                circleUser2.setOpenId("");
                circleUserService.updateById(circleUser2);
            }
            CircleUser circleUser = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(phone != null, "phone", phone));

            //如果用户不存在，则注册用户
            if (circleUser == null) {
                CircleUser circleUser1 = new CircleUser();
                circleUser1.setOpenId(wxOpenid);
                circleUser1.setCreateTime(LocalDateTime.now());
                circleUser1.setPhone(phone);
                circleUser1.setName("品讯科技");
                circleUser1.setHeadPic("https://yctk-1256675456.cos.ap-nanjing.myqcloud.com/1000001771303685..png");
                circleUser1.setOrganizationalId("42");
                circleUser1.setSex(1);
                circleUser1.setBirthYear(LocalDate.now().getYear());
                circleUserService.save(circleUser1);


                //填写默认信息 公司/个人简介
                CircleCompany company = new CircleCompany();
                company.setUid(circleUser1.getId());
                company.setDisplay(1);
                company.setCreateTime(LocalDateTime.now());
                company.setPic("[{\"url\":\"https://yctk-1256675456.cos.ap-nanjing.myqcloud.com/1000001651340966.jpg\"}]");
                company.setName("河南品讯网络科技有限公司");
                company.setIntroduce("河南品讯网络科技有限公司");
                company.setAddress("{\"name\":\"洛阳863创智广场\",\"lat\":34.621737613,\"lng\":112.49223158}");
                company.setDetailsAddress("3栋502");
                company.setPosition("员工");
                circleCompanyService.save(company);


                //保存注册记录 - 不进行去重
                UserRegLog log = new UserRegLog();
                log.setIphone(phone);
                log.setCreateTime(LocalDateTime.now());
                userRegLogService.save(log);

                circleUser = circleUser1;

            } else {

                if (circleUser.getIsDel() == 2) {
                    return R.failed("账号已停用");
                }


                if (StringUtils.isNotEmpty(circleUser.getToken())) {
                    redisTemplate.delete(circleUser.getToken());
                }
                circleUser.setOpenId(wxOpenid);
                circleUserService.updateById(circleUser);
            }

            JwtPayLoad payLoad = new JwtPayLoad((circleUser.getId().toString()), circleUser.getOpenId(), "xxxx");
            //创建token
            String token = JwtTokenUtil.generateToken(payLoad);


            redisHelper.getRedisTemplate().boundValueOps(token).set(circleUser.getId());
            CircleUser circleUser1 = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(wxOpenid != null, "open_id", wxOpenid));
            circleUser1.setToken(token);
            circleUserService.updateById(circleUser1);
            result.put("token", token);
            //分享是否开启
            try {
                CircleEnable circleEnable = circleEnableService.list().get(0);
                if (circleEnable != null) {
                    circleUser1.setType(circleEnable.getType());
                }
            } catch (Exception e) {
                System.out.println("开启分享失败");
            }
            result.put("circleUser", circleUser1);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok(result);

    }


    @GetMapping(value = "/login/wx")
    @ApiOperation("用户登录服务")
    @Inner(value = false)
    public Object loginVali(@RequestParam(value = "code", required = false) String code) {


        CircleWxInfo circleWxInfo = circleWxInfoService.list().get(0);
        String wxOpenid = null;
        final WxMaService wxService = WxMaConfiguration.getMaService(circleWxInfo.getAppid(), circleWxInfo.getSecret());
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            wxOpenid = session.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //登录并创建token
        CircleUser circleUser = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(wxOpenid != null, "open_id", wxOpenid));
        if (circleUser == null) {
            return R.ok("未找到此用户信息,请使用手机号验证码登录");
        }
        if (circleUser != null && circleUser.getIsTourists() == 2) {
            return R.failed("您不是会员,请使用游客登录");
        }
        if (circleUser != null && circleUser.getIsDel() == 2) {
            return R.failed("账户已停用");
        }


        JwtPayLoad payLoad = new JwtPayLoad((circleUser.getId().toString()), circleUser.getOpenId(), "xxxx");

        //创建token
        String token = JwtTokenUtil.generateToken(payLoad);
        //删除redis
        if (StringUtils.isNotEmpty(circleUser.getToken())) {
            redisTemplate.delete(circleUser.getToken());
        }
        //更新token
        circleUser.setToken(token);
        circleUserService.updateById(circleUser);
        redisHelper.getRedisTemplate().boundValueOps(token).set(circleUser.getId());
        //分享是否开启
        try {
            CircleEnable circleEnable = circleEnableService.list().get(0);
            if (circleEnable != null) {
                circleUser.setType(circleEnable.getType());
            }
        } catch (Exception e) {

        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("circleUser", circleUser);

        return R.ok(map);
    }


//    @Scheduled(cron = "0 0 0 * * ?")
//    @GetMapping("/initDataSource")
//    @Inner(value = false)
    public void runSql() {
        String mysqlUrl = "jdbc:mysql://rm-2ze0n774931bei71sko.mysql.rds.aliyuncs.com:3306/haoshanghui?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password  = "pinxun@2020";
        try {
            // 建立连接
            Connection conn = DriverManager.getConnection(mysqlUrl, username, password);

            // 创建ScriptRunner，用于执行SQL脚本
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            // 执行SQL脚本
            runner.runScript(Resources.getResourceAsReader("init/haoshanghui.sql"));

            // 关闭连接
            conn.close();

            // 若成功，打印提示信息
            System.out.println("====== SUCCESS ======");
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }


}







